package com.smart.village.big.screen.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.smart.village.big.screen.domain.BluePlateTags;
import com.smart.village.big.screen.domain.NewsVo;
import com.smart.village.big.screen.domain.PartyOrganizationTreeNode;
import com.smart.village.big.screen.domain.VillageOrganizationTreeNode;
import com.smart.village.big.screen.mapper.*;
import com.smart.village.big.screen.service.MicroSmartMoHeResidentService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class MicroSmartMoHeResidentServiceImpl implements MicroSmartMoHeResidentService {
    @Autowired
    private MicroSmartMoHeResidentMapper residentMapper;
    @Autowired
    private BenefitPeopleMapper benefitPeopleMapper;
    @Autowired
    private PartyOrganizationMapper partyOrganizationMapper;
    @Autowired
    private ACTMapper actMapper;
    @Autowired
    private NewsMapper newsMapper;

    @Override
    public JSONObject getThreeAffairsDisclosureList(String townNumber, String villageNumber,
                                                    String partOrganizationSerialNumber, String type,
                                                    String beginDate, String endDate,
                                                    int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> personalPointsAccountList = residentMapper.getThreeAffairsDisclosureList(townNumber, villageNumber, partOrganizationSerialNumber, type, beginDate, endDate);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(personalPointsAccountList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getThreeAffairsDisclosureDetail(String affairsSerialNumber) {
        JSONObject jsonObject = residentMapper.getThreeAffairsDisclosureDetail(affairsSerialNumber);
        jsonObject.put("Attachment_List", residentMapper.getThreeAffairsDisclosureDetailAttachmentList(affairsSerialNumber));
        return jsonObject;
    }

    @Override
    public JSONObject getSubsidyPolicyList(String year, String policyTypeSerialNumber, String search, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = Lists.newArrayList();
        if (policyTypeSerialNumber.equals("SPT000000000001")) {
            list = residentMapper.getSubsidyPolicyList(year, search);
        }
        if (policyTypeSerialNumber.equals("SPT000000000002")) {
            list = residentMapper.getSubsidyPolicyAgriculturalMachinery(year, search);
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getSubsidyPolicyDetail(String policySerialNumber, String policyTypeSerialNumber) {
        // 处理普通补贴政策(SPT000000000001)
        if (policyTypeSerialNumber.equals("SPT000000000001")) {
            JSONObject jsonObject = residentMapper.getSubsidyPolicyBySerialNumber(policySerialNumber);
            // 防止查询结果为null时出现NPE
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            jsonObject.put("Detail_List", residentMapper.getSubsidyPolicyDetailsBySerialNumber(policySerialNumber));
            return jsonObject;
        }

        // 处理农机补贴政策(SPT000000000002)
        if (policyTypeSerialNumber.equals("SPT000000000002")) {
            JSONObject jsonObject = residentMapper.getSubsidyPolicyAgriculturalMachineryBySerialNumber(policySerialNumber);

            // 默认返回空JSON对象而非null，避免调用方空指针

            // 防止查询结果为null时出现NPE
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            // 添加与类型1一致的Detail_List字段，保持数据结构统一
            jsonObject.put("Detail_List", Lists.newArrayList());
            return jsonObject;
        }
        return null;

    }

    @Override
    public JSONObject getDistrictIntroduction(String districtNumber) {
        JSONObject jsonObject = residentMapper.getDistrictIntroduction(districtNumber);
        if (jsonObject == null) {
            return new JSONObject();
        }
        jsonObject.put("Person_Cnt", residentMapper.getPersonCnt("", districtNumber));
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMyServiceMemberList(String iDCardNumber, String role) {
        return residentMapper.getMyServiceMemberList(iDCardNumber, role);
    }

    @Override
    public JSONObject getPatrolCheckInList(String phone, String beginDate, String endDate) {
        // 获取数据库中的打卡记录
        JSONObject jsonObject = new JSONObject();
        List<JSONObject> checkInRecords = residentMapper.getPatrolCheckInList(phone, beginDate, endDate);
        int totalCheckInCnt = residentMapper.getPatrolCheckInTotalCnt(phone, DateFormatUtils.format(new Date(), "yyyy"));
        jsonObject.put("totalCheckInCnt", totalCheckInCnt);
        jsonObject.put("list", checkInRecords);
//        // 提取已打卡日期（假设日期字段名为"check_date"，格式为yyyy-MM-dd）
//        Set<String> checkedDates = new HashSet<>();
//        for (JSONObject record : checkInRecords) {
//            String checkDate = record.getString("check_date");
//            if (checkDate != null) {
//                checkedDates.add(checkDate);
//            }
//        }
//
//        // 生成开始日期到结束日期的所有日期
//        List<JSONObject> resultList = Lists.newArrayList();
//        try {
//            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
//            LocalDate start = LocalDate.parse(beginDate, formatter);
//            LocalDate end = LocalDate.parse(endDate, formatter);
//
//            // 计算日期天数差
//            long days = ChronoUnit.DAYS.between(start, end);
//
//            // 遍历所有日期并标记打卡状态
//            for (long i = 0; i <= days; i++) {
//                LocalDate currentDate = start.plusDays(i);
//                String dateStr = currentDate.format(formatter);
//
//                JSONObject dateObj = new JSONObject();
//                dateObj.put("date", dateStr);
//                dateObj.put("checked", checkedDates.contains(dateStr) ? 1 : 0);
//                resultList.add(dateObj);
//            }
//        } catch (Exception e) {
//            // 日期格式错误处理
//            e.printStackTrace();
//            return Lists.newArrayList(); // 或返回错误信息
//        }

        return jsonObject;
    }

    @Override
    public List<JSONObject> getWorkTeamsByVillageNumber(String villageNumber) {
        List<JSONObject> workTeamsByVillageNumber = residentMapper.getWorkTeamsByVillageNumber(villageNumber);
        for (int i = 0; i < workTeamsByVillageNumber.size(); i++) {
            JSONObject jsonObject = workTeamsByVillageNumber.get(i);
            jsonObject.put("WorkTeamMember_List", residentMapper.getWorkTeamsMembersByTeamSerialNumber(jsonObject.getString("Work_Team_SerialNumber")));
        }
        return workTeamsByVillageNumber;
    }

    @Override
    public JSONObject getProjectOnlineNewsList(String NewsTerminal, String townNumber, String villageNumber, String beginDate, String endDate, String search, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> personalPointsAccountList = residentMapper.getProjectOnlineNewsList(NewsTerminal, townNumber, villageNumber, "NC0000000000076", beginDate, endDate, search);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(personalPointsAccountList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getVolunteerTeamsActivities(String status, String idCardNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> personalPointsAccountList = residentMapper.getVolunteerTeamsActivities(status, idCardNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(personalPointsAccountList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getVolunteerTeamsActivitiesDetail(String volunteerTeamsActivitiesSerialNumber) {
        return residentMapper.getVolunteerTeamsActivitiesDetail(volunteerTeamsActivitiesSerialNumber);
    }

    @Override
    public JSONObject getVillageActivities(String status, String idCardNumber, String villageNumber, String assembly, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> personalPointsAccountList = residentMapper.getVillageActivities(status, idCardNumber, villageNumber, assembly);
        for (JSONObject jsonObject : personalPointsAccountList) {
            List<JSONObject> villageActivitySerialNumber = residentMapper.getVillageActivitiesIfMyPartyIn(jsonObject.getString("Village_Activity_SerialNumber"), idCardNumber);
            if (!CollectionUtils.isEmpty(villageActivitySerialNumber)) {
               boolean ifMeCheckIn = false;
                for (JSONObject object : villageActivitySerialNumber) {
                    if(object.getString("Check_In_Datetime") != null && !Objects.equals(object.getString("Check_In_Datetime"), "")){
                        ifMeCheckIn = true;
                    }
                }
                if(ifMeCheckIn){
                    jsonObject.put("If_Me_Check_In", "1");
                    jsonObject.put("Village_Activity_Member_SerialNumber", villageActivitySerialNumber.get(0).getString("Village_Activity_Member_SerialNumber"));
                    jsonObject.put("Check_In_Datetime", villageActivitySerialNumber.get(0).getString("Check_In_Datetime"));
                }else{
                    jsonObject.put("If_Me_Check_In", "0");
                    jsonObject.put("Village_Activity_Member_SerialNumber", villageActivitySerialNumber.get(0).getString("Village_Activity_Member_SerialNumber"));
                    jsonObject.put("Check_In_Datetime", "");
                }

            } else {
                jsonObject.put("If_Me_Check_In", "0");
                jsonObject.put("Village_Activity_Member_SerialNumber", "");
                jsonObject.put("Check_In_Datetime", "");
            }
        }
        PageInfo<JSONObject> pageInfo = new PageInfo<>(personalPointsAccountList);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getVillageActivitiesDetail(String villageActivitiesSerialNumber, String iDCardNumber) {
        JSONObject villageActivitiesDetail = residentMapper.getVillageActivitiesDetail(villageActivitiesSerialNumber, iDCardNumber);
        if (ObjectUtils.isEmpty(villageActivitiesDetail)) {
            return new JSONObject();
        }
        List<JSONObject> villageActivitySerialNumber = residentMapper.getVillageActivitiesIfMyPartyIn(villageActivitiesDetail.getString("Village_Activity_SerialNumber"), iDCardNumber);
        if (!CollectionUtils.isEmpty(villageActivitySerialNumber)) {
            villageActivitiesDetail.put("If_Me_Check_In", "1");
            villageActivitiesDetail.put("Village_Activity_Member_SerialNumber", villageActivitySerialNumber.get(0).getString("Village_Activity_Member_SerialNumber"));
            villageActivitiesDetail.put("Check_In_Datetime", villageActivitySerialNumber.get(0).getString("Check_In_Datetime"));
        } else {
            villageActivitiesDetail.put("If_Me_Check_In", "0");
            villageActivitiesDetail.put("Village_Activity_Member_SerialNumber", "");
            villageActivitiesDetail.put("Check_In_Datetime", "");
        }
        return villageActivitiesDetail;
    }

    @Override
    public List<JSONObject> getListTypeByParentSerialNumber(String parentSerialNumber) {
        return residentMapper.getListTypeByParentSerialNumber(parentSerialNumber);
    }

    @Override
    public JSONObject getListManagement(String listTypeSerialNumber, String townNumber, String villageNumber, String level, String search, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> listManagement = residentMapper.getListManagement(listTypeSerialNumber, townNumber, villageNumber, level, search);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(listManagement);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        if(StringUtils.isNotEmpty(townNumber)){
            jsonObject.put("ifVillageThings",1);
        }else{
            jsonObject.put("ifVillageThings",0);
        }
        return jsonObject;
    }

    @Override
    public JSONObject getListManagementDetail(String listManagementSerialNumber) {
        JSONObject jsonObject = residentMapper.getListManagementDetail(listManagementSerialNumber);
        if (jsonObject != null) {
            jsonObject.put("List_Material_List", residentMapper.getListMaterial(listManagementSerialNumber));
            jsonObject.put("List_Management_Attachment", residentMapper.getListManagementAttachment(listManagementSerialNumber));
            return jsonObject;
        }
        return new JSONObject();
    }

    @Override
    public JSONObject getMyVillageSaleOrderList(String idCardNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyVillageSaleOrderList(idCardNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyComplaints(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotEmpty(status)) {
            if (status.equals("待指派")) {
                status = "提交";
            }
            if (status.equals("处理中")) {
                status = "处理";
            }
        }
        //source 小程序-民生诉求
        List<JSONObject> list = residentMapper.getMyComplaints(phone, status);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyComplaintsDetail(String complaintId) {
        return residentMapper.getMyComplaintsDetail(complaintId);
    }

    @Override
    public JSONObject getMyVillageSaleOrderIncome(String idCardNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyVillageSaleOrderIncome(idCardNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyVillageSaleOrderExpenditure(String idCardNumber, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyVillageSaleOrderExpenditure(idCardNumber);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyPoints(String idCardNumber) {
        return ObjectUtils.isEmpty(residentMapper.getMyPoints(idCardNumber))?new JSONObject():residentMapper.getMyPoints(idCardNumber);
    }

    @Override
    public JSONObject getThreeResourceDisclosureList(String townNumber, String villageNumber, String category, String beginDate, String endDate, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String NewsTerminal = "小程序-数智漠河/村民";
        List<JSONObject> list = residentMapper.getThreeResourceDisclosureList(townNumber, villageNumber, category, beginDate, endDate, NewsTerminal);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getNoticePublish(String townNumber, String villageNumber, int pageNum, int pageSize, int environment, String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> list = residentMapper.getNoticePublish(townNumber, villageNumber, environment, NewsTerminal);
        execFormatSubTitle(list);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getLawPopularization(String newsTagSerialNumber, int pageNum, int pageSize, int environment, String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> list = residentMapper.getLawPopularization(newsTagSerialNumber, environment, NewsTerminal);
        execFormatSubTitle(list);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getLawPopularizationTagList() {
        return residentMapper.getLawPopularizationTagList();
    }

    @Override
    public JSONObject getAntiPhishing(String newsTagSerialNumber, int pageNum, int pageSize, int environment, String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> list = residentMapper.getAntiPhishing(newsTagSerialNumber, environment, NewsTerminal);
        execFormatSubTitle(list);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getAntiPhishingTagList() {
        return residentMapper.getAntiPhishingTagList();
    }

    @Override
    public JSONObject getNewsDetail(String newsSerialNumber) {
        JSONObject news = residentMapper.getNewsDetail(newsSerialNumber);
        List<JSONObject> newsPictureList = residentMapper.getNewsPictureList(newsSerialNumber);
        news.put("newsPictureList", newsPictureList);
        residentMapper.updateNewsViewsCount(newsSerialNumber);
        return news;
    }

    @Override
    public JSONObject getIntegralMall(String townNumber, String villageNumber, String categoryName, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getIntegralMall(townNumber, villageNumber, categoryName);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getIntegralMallCategory() {
        return residentMapper.getIntegralMallCategory();
    }

    @Override
    public JSONObject getIntegralMallDetail(String specificationsSerialNumber) {
        return residentMapper.getIntegralMallDetail(specificationsSerialNumber);
    }

    @Override
    public JSONObject getMicroPartyMemberInformationByPhone(String phone) {
        return ObjectUtils.isEmpty(residentMapper.getMicroPartyMemberInformationByPhone(phone))?new JSONObject():residentMapper.getMicroPartyMemberInformationByPhone(phone);
    }

    @Override
    public JSONObject getIntegralApplicationList(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getIntegralApplicationList(phone, status);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getIntegralApplicationDetail(String personalPointsApplicationSerialNumber) {
        return residentMapper.getIntegralApplicationDetail(personalPointsApplicationSerialNumber);
    }

    @Override
    public JSONObject getMySubsidyPolicyList(String idCardNumber, String townNumber, String villageNumber, String search, String status, String year,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMySubsidyPolicyList(idCardNumber, townNumber, villageNumber, search, status,year);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMySubsidyPolicyDetail(String applicationSerialNumber) {
        List<JSONObject> detailList = residentMapper.getMySubsidyPolicyDetail(applicationSerialNumber);

        if (!CollectionUtils.isEmpty(detailList)) {
            for (JSONObject jsonObject : detailList) {
                List<JSONObject> actualDistributeList = residentMapper.getSubsidyApplicationActualDistributeListByApplicationDistributionNumber(jsonObject.getString("Application_Distribution_SerialNumber"));
                if (CollectionUtils.isEmpty(actualDistributeList) || null==actualDistributeList.get(0)) {
                    jsonObject.put("actualDistributeList", Lists.newArrayList());
                }else {
                    jsonObject.put("actualDistributeList", actualDistributeList);
                }
                BigDecimal totalActualAmount = BigDecimal.ZERO;
                for (JSONObject actualDistribute : actualDistributeList) {
                    if (null == actualDistribute || null == actualDistribute.getBigDecimal("Application_Amount")) {
                        continue;
                    }
                    totalActualAmount = totalActualAmount.add(actualDistribute.getBigDecimal("Application_Amount"));
                }
                jsonObject.put("totalActualAmount", totalActualAmount);
                List<JSONObject> list = residentMapper.getMySubsidyPolicyCorpList(jsonObject.getString("Policy_SerialNumber"));
                jsonObject.put("cropList", list);

                List<JSONObject> mySubsidyApplicationAttachment = residentMapper.getMySubsidyApplicationAttachment(applicationSerialNumber);
                jsonObject.put("mySubsidyApplicationAttachment", mySubsidyApplicationAttachment);
            }
        } else {
            return Lists.newArrayList();
        }
        return detailList;
    }

    @Override
    public JSONObject getMySubsidyPolicyAgriculturalMachineryList(String idCardNumber, String search, String status, String year,int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMySubsidyPolicyAgriculturalMachineryList(idCardNumber, search, status,year);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMySubsidyPolicyAgriculturalMachineryDetail(String applicationSerialNumber) {
        List<JSONObject> mySubsidyPolicyAgriculturalMachineryDetail = residentMapper.getMySubsidyPolicyAgriculturalMachineryDetail(applicationSerialNumber);
        for (JSONObject jsonObject : mySubsidyPolicyAgriculturalMachineryDetail) {
            List<JSONObject> actualDistributeList = residentMapper.getSubsidyApplicationActualDistributeListByApplicationDistributionNumber(jsonObject.getString("Application_Distribution_SerialNumber"));
            BigDecimal totalActualAmount = BigDecimal.ZERO;
            for (JSONObject actualDistribute : actualDistributeList) {
                if (actualDistribute!= null) {
                    totalActualAmount = totalActualAmount.add(actualDistribute.getBigDecimal("Application_Amount"));
                }
            }
            jsonObject.put("totalActualAmount", totalActualAmount);
            jsonObject.put("actualDistributeList", actualDistributeList);
            List<JSONObject> mySubsidyApplicationAttachment = residentMapper.getMySubsidyApplicationAttachment(applicationSerialNumber);
            jsonObject.put("mySubsidyApplicationAttachment", mySubsidyApplicationAttachment);
        }
        return mySubsidyPolicyAgriculturalMachineryDetail;
    }

    @Override
    public JSONObject getMyComplaintMoheList(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        //source 小程序-线上举报
        List<JSONObject> list = residentMapper.getMyComplaintMoheList(phone, status);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyRatingMoheList(String phone, String status, String source, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyRatingMoheList(phone, status, source);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyRatingMoheDetail(String complaintId, String source) {
        return residentMapper.getMyRatingMoheDetail(complaintId, source);
    }

    @Override
    public JSONObject getMyAllShopList(String iDCardNumber, String category, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyAllShopList(iDCardNumber, category);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyShopBookList(String iDCardNumber, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyShopBookList(iDCardNumber, status);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyHelpList(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotEmpty(status)) {
            if (status.equals("处理中") || status.equals("待办理")) {
                status = "0";
            }
            if (status.equals("已完成") || status.equals("已办结")) {
                status = "2";
            }
        }

        List<JSONObject> list = residentMapper.getMyHelpList(phone, status);
        list.forEach(jsonObject -> {
            if ("0".equals(jsonObject.getString("Row_Status"))) {
                jsonObject.put("Row_Status_Name", "处理中");
            }

            if ("2".equals(jsonObject.getString("Row_Status"))) {
                jsonObject.put("Row_Status_Name", "已完成");
            }

        });
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyApplyList(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        // 目前只有两个 房屋修缮和宅基地翻建
        List<JSONObject> list = residentMapper.getMyApplyList(phone, status);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyHelpListDetail(String applicationSerialNumber) {
        JSONObject applyDetail = residentMapper.getMyHelpListDetail(applicationSerialNumber);
        if (ObjectUtils.isEmpty(applyDetail)) {
            return new JSONObject();
        }
        applyDetail.put("Attachment_List", residentMapper.getMyHelpListDetailAttachList(applicationSerialNumber));
        List<JSONObject> replyList = residentMapper.getHelpListDetailReplyList(applicationSerialNumber);
        applyDetail.put("Reply_List", replyList);
        replyList.forEach(reply -> {
            List<JSONObject> replyAttachList = residentMapper.getHelpListDetailReplyAttachList(reply.getString("Application_Reply_SerialNumber"));
            reply.put("Reply_Attach_List", replyAttachList);
        });
        return applyDetail;
    }

    @Override
    public JSONObject getMyApplyDetail(String projectSerialNumber) {
        JSONObject applyDetail = residentMapper.getMyApplyDetail(projectSerialNumber);
        if (ObjectUtils.isEmpty(applyDetail)) {
            return new JSONObject();
        }
        applyDetail.put("Attachment_List", residentMapper.getMyApplyDetailAttachList(projectSerialNumber));
        return applyDetail;
    }

    @Override
    public JSONObject getOrganizationPartOne(String townNumber, String villageNumber) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Person_Cnt", residentMapper.getPersonCnt(townNumber, villageNumber));
        jsonObject.put("Hu_Cnt", residentMapper.getHuCnt(townNumber, villageNumber));
        jsonObject.put("Party_Member_Cnt", residentMapper.getPartyMemberCnt(townNumber, villageNumber));
        jsonObject.put("Canji_Person_Cnt", residentMapper.getCanjiPersonCnt(townNumber, villageNumber));
        jsonObject.put("Pinkun_Person_Cnt", residentMapper.getPinkunPersonCnt(townNumber, villageNumber));
        jsonObject.put("Tuiyi_Junren_Person_Cnt", residentMapper.getTuiyiJunrenPersonCnt(townNumber, villageNumber));
        return jsonObject;
    }

    @Override
    public List<JSONObject> getVillageContactList(String townNumber, String villageNumber, String search) {
        return residentMapper.getVillageContactList(townNumber, villageNumber, search);
    }

    @Override
    public List<JSONObject> getPartyOrgPositionInformation(String villageNumber) {
        List<String> partyOrganizationList = partyOrganizationMapper.getPartyOrganizationSerialNumber(villageNumber);
        if (CollectionUtils.isEmpty(partyOrganizationList)) {
            return Lists.newArrayList();
        }
        return partyOrganizationMapper.getMicroPositionInformation(partyOrganizationList.get(0));
    }

    @Override
    public JSONObject getPartyOrgPositionInformationTree(String villageNumber) {
        List<String> partyOrganizationList = partyOrganizationMapper.getPartyOrganizationSerialNumber(villageNumber);
        if (CollectionUtils.isEmpty(partyOrganizationList)) {
            return new JSONObject();
        }
        String partyOrganizationSerialNumber = partyOrganizationList.get(0);
        String maxTenureSerialNumber = partyOrganizationMapper.getMaxTenureSerialNumber(partyOrganizationSerialNumber);
        if (maxTenureSerialNumber == null) {
            return new JSONObject();
        }
        JSONObject maxPartyOrgPositionTenure = benefitPeopleMapper.getPartyOrgPositionTenure(maxTenureSerialNumber);
        List<JSONObject> partyOrganizationPositionData = partyOrganizationMapper.getPartyOrganizationPositionTree(maxTenureSerialNumber, partyOrganizationSerialNumber);
        PartyOrganizationTreeNode partyOrganizationTreeNode = buildTree(partyOrganizationPositionData);
        maxPartyOrgPositionTenure.put("PartyOrganizationTreeNode", partyOrganizationTreeNode);
        return maxPartyOrgPositionTenure;

    }

    @Override
    public List<JSONObject> getVillagePositionInformation(String villageNumber) {
        return benefitPeopleMapper.getVillageConcatPersonList(villageNumber);
    }

    @Override
    public JSONObject getVillagePositionInformationTree(String villageNumber) {
        String maxTenureSerialNumber = benefitPeopleMapper.getMaxVillageTenureSerialNumber(villageNumber);
        if (maxTenureSerialNumber == null) {
            return new JSONObject();
        }
        JSONObject maxVillageTenure = benefitPeopleMapper.getMaxVillageTenure(maxTenureSerialNumber);
        List<JSONObject> villageOrganizationPositionData = benefitPeopleMapper.getVillageOrganizationPositionTree(maxTenureSerialNumber);
        VillageOrganizationTreeNode villageOrganizationTreeNode = buildVillageTree(villageOrganizationPositionData);
        maxVillageTenure.put("VillageOrganizationTreeNode", villageOrganizationTreeNode);
        return maxVillageTenure;
    }

    @Override
    public List<JSONObject> getPartyOrgListByTownVillageNumber(String townNumber, String villageNumber) {
        return residentMapper.getPartyOrgListByTownVillageNumber(townNumber, villageNumber);
    }

    @Override
    public List<JSONObject> getVillageLeaderPositionInformation(String villageNumber) {
        return residentMapper.getVillageLeaderPositionInformation(villageNumber);
    }

    @Override
    public JSONObject getConvenientServiceList(String townNumber, String villageNumber, String search, String category, String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String[] split = category.split(",");
        if(StringUtils.isBlank(category)){
            split = null;
        }
        List<JSONObject> list = residentMapper.getConvenientServiceList(townNumber, villageNumber, search, split, type);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getConvenientServiceDetail(String agriculturalMachinerySerialNumber) {
        JSONObject convenientServiceDetail = residentMapper.getConvenientServiceDetail(agriculturalMachinerySerialNumber);
        if (ObjectUtils.isEmpty(convenientServiceDetail)) {
            return new JSONObject();
        }
        convenientServiceDetail.put("Attachment_List", residentMapper.getConvenientServiceDetailAttachList(agriculturalMachinerySerialNumber));
        return convenientServiceDetail;
    }

    @Override
    public JSONObject getMyConvenientServiceList(String phone, String category, String type, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyConvenientServiceList(phone, category, type);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMicroAccountInformation(String phone, String villageNumber) {
        JSONObject jsonObject = residentMapper.getMicroAccountInformation(phone);
        List<JSONObject> Position_Information = residentMapper.getMicroAccountInformationPosition(jsonObject.getString("idCardNumber"),villageNumber);
        if(CollectionUtils.isEmpty(Position_Information)){
            jsonObject.put("Position_Information", Lists.newArrayList());
        }else{
            jsonObject.put("Position_Information", Position_Information);
        }

        if (ObjectUtils.isEmpty(jsonObject)) {
            return new JSONObject();
        }
        jsonObject.remove("idCardNumber");
        return jsonObject;
    }

    @Override
    public List<JSONObject> getLawMatrix(String type, String search) {
        return residentMapper.getLawMatrix(type, search);
    }

    @Override
    public List<JSONObject> getConvenientServiceCategory() {
        return residentMapper.getConvenientServiceCategory();
    }

    @Override
    public List<BluePlateTags> getAllBluePlateTags(String tagSerialNumber) {
        return actMapper.getAllBluePlateTags(tagSerialNumber);
    }

    @Override
    public List<JSONObject> getMapBluePlateByTagsAndCoords(String tagSerialNumber, String search, String km, String currentCoords) {
        return residentMapper.getMapBluePlateByTagsAndCoords(tagSerialNumber, search, km, currentCoords);
    }

    @Override
    public JSONObject getMapBluePlateDetail(String bluePlateSerialNumber, String tagSerialNumber) {
        JSONObject jsonObject = residentMapper.getMapBluePlateDetail(bluePlateSerialNumber, tagSerialNumber);
        List<JSONObject> bluePlateImageList = residentMapper.getBluePlateImageList(bluePlateSerialNumber);
        jsonObject.put("Blue_Plate_Image_List", bluePlateImageList);
        return jsonObject;
    }

    @Override
    public List<JSONObject> getCarouselConfig() {
        return residentMapper.getCarouselConfig();
    }

    @Override
    public List<JSONObject> getMyAllShopListNoPage(String iDCardNumber, String category) {
        return residentMapper.getMyAllShopList(iDCardNumber, category);
    }

    @Override
    public JSONObject getCadreSelectionAppointment(String townNumber, String villageNumber, String yearMonth, int pageNum, int pageSize, int environment, String NewsTerminal) {
        PageHelper.startPage(pageNum, pageSize);
        List<NewsVo> list = residentMapper.getCadreSelectionAppointment(townNumber, villageNumber, yearMonth, NewsTerminal);
        execFormatSubTitle(list);
        PageInfo<NewsVo> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getLeaveWord(String phone, String replyStatus, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getLeaveWord(phone, replyStatus);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getAgricultureResourceServiceList(String townNumber, String villageNumber, String search) {
        return residentMapper.getAgricultureResourceServiceList(townNumber, villageNumber, search);
    }

    @Override
    public JSONObject getAgricultureResourceServiceDetail(String shopSerialNumber) {
        JSONObject deliciousFoodShopDetail = residentMapper.getAgricultureResourceServiceDetail(shopSerialNumber);
        List<JSONObject> dishInfoList = residentMapper.getAgricultureResourceList(shopSerialNumber);
        deliciousFoodShopDetail.put("Dish_Info_List", dishInfoList);
        return deliciousFoodShopDetail;
    }

    @Override
    public List<JSONObject> getBeneficialPeopleLogoList(String parentSerialNumber) {
        List<JSONObject> navList = new ArrayList<>();
        List<JSONObject> listTypeByParentSerialNumber = residentMapper.getListTypeByParentSerialNumber(parentSerialNumber);
        for (JSONObject listType : listTypeByParentSerialNumber) {
            List<JSONObject> subList = residentMapper.getListTypeByParentSerialNumber(listType.getString("List_Type_SerialNumber"));
            if (!CollectionUtils.isEmpty(subList)) {
                JSONObject sub = subList.get(0);
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("title", sub.getString("List_Type"));
                jsonObject.put("ico", sub.getString("Icon"));
                jsonObject.put("url", "/villageResite/materials/materials");
                jsonObject.put("id", sub.getString("List_Type_SerialNumber"));
                navList.add(jsonObject);
            }
//            else {
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("title", listType.getString("List_Type"));
//                jsonObject.put("ico", listType.getString("Icon"));
//                jsonObject.put("url", "/villageResite/materials/materials");
//                jsonObject.put("id", listType.getString("List_Type_SerialNumber"));
//                navList.add(jsonObject);
//            }
            if (navList.size() == 7) {
                break;
            }
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("title", "更多");
        jsonObject.put("ico", "publicWelfareServices-nav-8.png");
        jsonObject.put("url", "/villageResite/morePublicWelfare/morePublicWelfare");
        jsonObject.put("id", parentSerialNumber);
        navList.add(jsonObject);

        return navList;
    }

    @Override
    public List<JSONObject> getBeneficialPeopleLogoListMore(String parentSerialNumber) {
        List<JSONObject> navList = new ArrayList<>();
        if ("more".equals(parentSerialNumber)) {
            parentSerialNumber = "LT0000000000001";
        }
        List<JSONObject> listTypeByParentSerialNumber = residentMapper.getListTypeByParentSerialNumber(parentSerialNumber);
        for (JSONObject listType : listTypeByParentSerialNumber) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("title", listType.getString("List_Type"));
            List<JSONObject> subList = residentMapper.getListTypeByParentSerialNumber(listType.getString("List_Type_SerialNumber"));
            List<JSONObject> items = new ArrayList<>();
            if (!CollectionUtils.isEmpty(subList)) {
                for (JSONObject object : subList) {
                    JSONObject jsonObject1 = new JSONObject();
                    jsonObject1.put("text", object.getString("List_Type"));
                    jsonObject1.put("icon", object.getString("Icon"));
                    jsonObject1.put("id", object.getString("List_Type_SerialNumber"));
                    items.add(jsonObject1);
                }
            }
            jsonObject.put("items", items);
            navList.add(jsonObject);
        }
        return navList;
    }

    @Override
    public JSONObject getMyRoundTripRegistrationList(String phone, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<JSONObject> list = residentMapper.getMyRoundTripRegistrationList(phone);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyRoundTripRegistrationDetail(String registrationSerialNumber) {
        JSONObject jsonObject = residentMapper.getMyRoundTripRegistrationDetail(registrationSerialNumber);
        List<JSONObject> villageProjectLogList = residentMapper.getMyRoundTripRegistrationEntourageList(registrationSerialNumber);
        jsonObject.put("villageProjectLogList", villageProjectLogList);
        return jsonObject;
    }

    @Override
    public JSONObject getMyVillageProject(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        String[] split = {};
        if (StringUtils.isNotEmpty(status)) {
            split = status.split(",");
        }
        List<JSONObject> list = residentMapper.getMyVillageProject(phone,split);
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public JSONObject getMyVillageProjectDetail(String projectSerialNumber) {
        JSONObject jsonObject = residentMapper.getMyVillageProjectDetail(projectSerialNumber);
        jsonObject.put("Attachment_List", residentMapper.getMyApplyDetailAttachList(projectSerialNumber));
        List<JSONObject> myVillageProjectLogs = residentMapper.getMyVillageProjectLogs(projectSerialNumber);
        for (JSONObject myVillageProjectLog : myVillageProjectLogs) {
            List<JSONObject> attachment = residentMapper.getMyVillageProjectLogsAttachment(myVillageProjectLog.getString("Village_Project_Log_SerialNumber"));
            myVillageProjectLog.put("Log_Attachment", attachment);
        }
        jsonObject.put("VillageProjectLogs", myVillageProjectLogs);
        return jsonObject;
    }

    @Override
    public List<JSONObject> getThreeAffairsDisclosureTitleList(String type, String townNumber, String villageNumber,String beginDate,String endDate) {
        if(type.equals("三务公开")) {
            List<JSONObject> threeAffairsTitle = residentMapper.getThreeAffairsDisclosureType();

            threeAffairsTitle.forEach(jsonObject -> {
                List<JSONObject> list = residentMapper.getThreeAffairsDisclosureList(
                        townNumber, villageNumber, "", jsonObject.getString("value"), beginDate, endDate);
                jsonObject.put("label", jsonObject.getString("label") + "(" + list.size() + ")");
            });


            return threeAffairsTitle;
        }
        if(type.equals("三资公开")) {
             //获取三个 三资的类型名称
            List<JSONObject> threeResourceTitle = residentMapper.getThreeResourceDisclosureType();
            for (JSONObject jsonObject : threeResourceTitle) {
                String NewsTerminal = "小程序-数智漠河/村民";
                List<JSONObject> list = residentMapper.getThreeResourceDisclosureList(townNumber, villageNumber, jsonObject.getString("value"),
                        beginDate, endDate, NewsTerminal);
                jsonObject.put("label", jsonObject.getString("label") + "(" + list.size() + ")");
            }
            return threeResourceTitle;

        }
        return Lists.newArrayList();
    }

    @Override
    public JSONObject getMyComplaintMoheDetail(String complaintId) {
        JSONObject jsonObject = residentMapper.getMyComplaintMoheDetail(complaintId);
        jsonObject.put("Attachment_List", residentMapper.getMyComplaintMoheDetailAttachment(complaintId));
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMyContractNatureResourceList(String iDCardNumber) {
        return residentMapper.getMyContractNatureResourceList(iDCardNumber);
    }

    @Override
    public JSONObject getMyBenefitList(String phone, String status, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        if (StringUtils.isNotEmpty(status)) {
            if (status.equals("处理中") || status.equals("待办理")) {
                status = "0";
            }
            if (status.equals("已完成") || status.equals("已办结")) {
                status = "2";
            }
        }

        List<JSONObject> list = residentMapper.getMyBenefitList(phone, status);
        list.forEach(jsonObject -> {
            if ("0".equals(jsonObject.getString("Row_Status"))) {
                jsonObject.put("Row_Status_Name", "处理中");
            }

            if ("2".equals(jsonObject.getString("Row_Status"))) {
                jsonObject.put("Row_Status_Name", "已完成");
            }

        });
        PageInfo<JSONObject> pageInfo = new PageInfo<>(list);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("list", pageInfo.getList());
        jsonObject.put("total", pageInfo.getTotal());
        return jsonObject;
    }

    @Override
    public List<JSONObject> getMyGridMemberListByIdCardNumber(String iDCardNumber) {
        return residentMapper.getMyGridMemberListByIdCardNumber(iDCardNumber);
    }

    @Override
    public JSONObject getSignInformation(String yearMonth,String phone) {
        String ls_Month = yearMonth.substring(yearMonth.indexOf("-") + 1);
        String ls_Year = yearMonth.substring(0, yearMonth.indexOf("-"));
        YearMonth yearMonthParam = YearMonth.of(Integer.parseInt(ls_Year), Integer.parseInt(ls_Month));

        List<JSONObject> jsonArraySignInLog = residentMapper.getSignInformationList(phone,yearMonth);
        LinkedHashSet<JSONObject> hashSet = Sets.newLinkedHashSet();
        hashSet.addAll(jsonArraySignInLog);
        JSONObject jsonObject_Data = new JSONObject();
        jsonObject_Data.put("SignInMonth", jsonArraySignInLog.size());
        jsonObject_Data.put("NoSignInMonth", yearMonthParam.lengthOfMonth() - hashSet.size());
        jsonObject_Data.put("ContinuousSignInDay", hashSet.size());

        List<String> dataList = new ArrayList<>();
        hashSet.forEach(jsonObject -> {
            dataList.add(jsonObject.getString("Sign_In_Date"));
        });

        jsonObject_Data.put("data", dataList);
        return jsonObject_Data;
    }

    public static VillageOrganizationTreeNode buildVillageTree(List<JSONObject> data) {
        Map<String, VillageOrganizationTreeNode> nodeMap = new HashMap<>();
        VillageOrganizationTreeNode root = null;

        // Step 1: Create all nodes and store them in a map
        for (JSONObject row : data) {
            String serialNumber = ObjectUtils.isEmpty(row.get("Tenure_Position_SerialNumber")) ? "" : row.getString("Tenure_Position_SerialNumber");
            String parentSerialNumber = ObjectUtils.isEmpty(row.get("Parent_SerialNumber")) ? "" : row.getString("Parent_SerialNumber");
            String position = ObjectUtils.isEmpty(row.get("Village_Position")) ? "" : row.getString("Village_Position");
            String personalName = ObjectUtils.isEmpty(row.get("Personal_Name")) ? "" : row.getString("Personal_Name");
            String pictureURL = ObjectUtils.isEmpty(row.get("Avatar")) ? "" : row.getString("Avatar");
            String contactPhone = ObjectUtils.isEmpty(row.get("Contact_Phone")) ? "" : row.getString("Contact_Phone");

            VillageOrganizationTreeNode node = new VillageOrganizationTreeNode(serialNumber, parentSerialNumber, position, personalName, pictureURL, contactPhone);
            nodeMap.put(serialNumber, node);

            // Identify the root node (no parent)
            if (parentSerialNumber == null || parentSerialNumber.isEmpty()) {
                root = node;
            }
        }

        // Step 2: Build the tree structure by linking parent and children
        for (JSONObject row : data) {
            String serialNumber = ObjectUtils.isEmpty(row.get("Tenure_Position_SerialNumber")) ? "" : row.getString("Tenure_Position_SerialNumber");
            String parentSerialNumber = ObjectUtils.isEmpty(row.get("Parent_SerialNumber")) ? "" : row.getString("Parent_SerialNumber");

            if (parentSerialNumber != null && !parentSerialNumber.isEmpty()) {
                VillageOrganizationTreeNode childNode = nodeMap.get(serialNumber);
                VillageOrganizationTreeNode parentNode = nodeMap.get(parentSerialNumber);
                if (parentNode != null) {
                    if (childNode != null) {
                        parentNode.addChild(childNode);
                    }
                }
            }
        }

        return root;
    }

    public static PartyOrganizationTreeNode buildTree(List<JSONObject> data) {
        Map<String, PartyOrganizationTreeNode> nodeMap = new HashMap<>();
        PartyOrganizationTreeNode root = null;

        // Step 1: Create all nodes and store them in a map
        for (JSONObject row : data) {
            String serialNumber = ObjectUtils.isEmpty(row.get("Tenure_Position_SerialNumber")) ? "" : row.getString("Tenure_Position_SerialNumber");
            String parentSerialNumber = ObjectUtils.isEmpty(row.get("Parent_SerialNumber")) ? "" : row.getString("Parent_SerialNumber");
            String position = ObjectUtils.isEmpty(row.get("Party_Position")) ? "" : row.getString("Party_Position");
            String personalName = ObjectUtils.isEmpty(row.get("Personal_Name")) ? "" : row.getString("Personal_Name");
            String pictureURL = ObjectUtils.isEmpty(row.get("pictureURL")) ? "" : row.getString("pictureURL");

            PartyOrganizationTreeNode node = new PartyOrganizationTreeNode(serialNumber, parentSerialNumber, position, personalName, pictureURL);
            nodeMap.put(serialNumber, node);

            // Identify the root node (no parent)
            if (parentSerialNumber == null || parentSerialNumber.isEmpty()) {
                root = node;
            }
        }

        // Step 2: Build the tree structure by linking parent and children
        for (JSONObject row : data) {
            String serialNumber = ObjectUtils.isEmpty(row.get("Tenure_Position_SerialNumber")) ? "" : row.getString("Tenure_Position_SerialNumber");
            String parentSerialNumber = ObjectUtils.isEmpty(row.get("Parent_SerialNumber")) ? "" : row.getString("Parent_SerialNumber");

            if (parentSerialNumber != null && !parentSerialNumber.isEmpty()) {
                PartyOrganizationTreeNode childNode = nodeMap.get(serialNumber);
                PartyOrganizationTreeNode parentNode = nodeMap.get(parentSerialNumber);
                if (parentNode != null) {
                    if (childNode != null) {
                        parentNode.addChild(childNode);
                    }
                }
            }
        }

        return root;
    }

    private void execFormatSubTitle(List<NewsVo> newsVoList) {
        newsVoList.forEach(newsVo -> {
            String newsSubTitle = newsVo.getNewsSubTitle();
            if (!StringUtils.isEmpty(newsSubTitle)) {
                Document doc = Jsoup.parse(newsSubTitle);

                // 查找第一个<p>标签
                Elements paragraphs = doc.select("p");
                if (paragraphs.size() > 0) {
                    Element firstParagraph = paragraphs.first(); // 获取第一个<p>标签
                    String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                    if (content.length() > 70) {
                        content = content.substring(0, 67) + "...";
                    }
                    newsVo.setNewsSubTitle(content);
                    return;
                } else {
                    Elements h1 = doc.select("h1");
                    Elements h2 = doc.select("h2");
                    Elements h3 = doc.select("h3");
                    Elements h4 = doc.select("h4");
                    Elements h5 = doc.select("h5");
                    Elements ul = doc.select("ul");
                    Elements ol = doc.select("ol");
                    Elements li = doc.select("li");
                    Elements div = doc.select("div");
                    Elements span = doc.select("span");
                    Elements strong = doc.select("strong");
                    if (h1.size() > 0) {
                        Element firstParagraph = h1.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h2.size() > 0) {
                        Element firstParagraph = h2.first(); // 获取第一个<h2>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h3.size() > 0) {
                        Element firstParagraph = h3.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h4.size() > 0) {
                        Element firstParagraph = h4.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                    if (h5.size() > 0) {
                        Element firstParagraph = h5.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (ul.size() > 0) {
                        Element firstParagraph = ul.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (ol.size() > 0) {
                        Element firstParagraph = ol.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (div.size() > 0) {
                        Element firstParagraph = div.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (span.size() > 0) {
                        Element firstParagraph = span.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (strong.size() > 0) {
                        Element firstParagraph = strong.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    } if (li.size() > 0) {
                        Element firstParagraph = li.first(); // 获取第一个<h1>标签
                        String content = firstParagraph.text(); // 获取标签的内容 如果超长 则处理为...
                        if (content.length() > 70) {
                            content = content.substring(0, 67) + "...";
                        }
                        newsVo.setNewsSubTitle(content);
                        return;
                    }
                }
            }
        });
    }
}
